package main.flex.connectivity
{
	import flash.events.AsyncErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.NetConnection;
	
	[Event(name="onConnect", type="flash.events.NetStatusEvent")]
	
	public class NetConnectionManager extends NetConnection
	{
		private static var _instance : NetConnectionManager;
		
		public function NetConnectionManager()
		{
			super();
			addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
			addEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
		
		public static function getInstance() : NetConnectionManager
		{
			if(!_instance)
			{
				_instance = new NetConnectionManager();
			} 
			return _instance;
		}
		
		public function createNetConnection(command:String, ... arguments):void
		{
			arguments.unshift(command);
			super.connect.apply(this, arguments);
		}
		
		protected function onConnectionStatus(event:NetStatusEvent):void
		{
			trace("#OnConnectionStatusEvent#" + event.info.code);
			
			var infoObjectsArray:Array = event.info.code.split(".");
			
			if(infoObjectsArray[1] == "Connect"){
				switch (infoObjectsArray[2])
				{
					case "Success":
					dispatchEvent(new NetStatusEvent("onConnect", false, false, event.info));
					break;
					
					case "Closed":
					break;
				}
			}
		}
		
		protected function onSecurityError(event:SecurityErrorEvent):void
		{
			trace("#OnSecurityError#" + event.text);
		}
		
		protected function onAsyncError(event:AsyncErrorEvent):void
		{
			trace("#OnAsyncError#" + event.error.message);
		}
		
		protected function onIOError(event:IOErrorEvent):void
		{
			trace("#OnIOError#" + event.text)
		}
		
	}
}